﻿function initPasteDragImg(Editor){
    var doc = document.getElementById(Editor.id)
    doc.addEventListener('paste', function (event) {
        var items = (event.clipboardData || window.clipboardData).items;
        var file = null;
        if (items && items.length) {
            // 搜索剪切板items
            for (var i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    file = items[i].getAsFile();
                    break;
                }
            }
        } else {
            console.log("当前浏览器不支持");
            return;
        }
        if (!file) {
            console.log("粘贴内容非图片");
            return;
        }
        uploadImg(file, Editor);
    });
    var dashboard = document.getElementById(Editor.id)
    dashboard.addEventListener("dragover", function (e) {
        e.preventDefault()
        e.stopPropagation()
    })
    dashboard.addEventListener("dragenter", function (e) {
        e.preventDefault()
        e.stopPropagation()
    })
    dashboard.addEventListener("drop", function (e) {
        e.preventDefault()
        e.stopPropagation()
     var files = this.files || e.dataTransfer.files;
     uploadImg(files[0],Editor);
     })
}
function uploadImg(file,Editor){
    var formData = new FormData();
    var fileName=new Date().getTime()+"."+file.name.split(".").pop();
    formData.append('file', file,file.name);
    $.ajax({
    	"type": 'POST',
        "url": Editor.settings.imageUploadURL,//获取我们配置的url
        "data": formData,
        "dateType": "json",
        "processData": false,
        "contentType": false,
        "mimeType": "multipart/form-data",
        success: function(ret){
        	var json = $.parseJSON(ret);
            console.log(json)
        	if(json.success){
        		var url = json.url;
        		var type = json.type;
        		var fname = json.filename;
        		console.log(url)
        		console.log(type)
        		if(/(png|jpg|jpeg|gif|bmp|ico|image)/.test(type)){
                    Editor.insertValue("![]("+url+")");
                }else{
                    Editor.insertValue("[Download File : " + fname + "](" + url +")");
                }
        	}else{
        		alert("上传失败");
        	}

        },
        error: function (err){
            console.log('请求失败')
        }
    });
}



$(function r1() {
    $('li.rightLi').contextmenu(function (e) {
        var menu=[
            ['新建Markdown',
                function (e) {
                    var path = $(e.data).children().attr('href');
                    var ext = '.md';
                    buildNewFile(path, ext);
                }
            ],
            ['新建Excel(.xlsx)',
                function (e) {
                    var path = $(e.data).children().attr('href');
                    var ext = '.xlsx';
                    buildNewFile(path, ext);

                }
            ],
            [
                '上传文件',
                function (e) {
                    var linkUrl = $(e.data).children().attr('href');
                    var inputLink = document.getElementById('link')
                    inputLink.setAttribute('value', linkUrl)
                    // window.open('/markdown/uploadFile/?link=' + linkUrl, 'UploadImage',
                    // "top=450,left=600,height=380,width=800,status=yes,toolbar=no,menubar=no,location=0,channelmode=0")
                    $("#layBox").tooltip("alert",{
                        'title':"文件列表-上传文件",
                        'backgroundColor': '#c8e5e1',
                        'width':'600px',
                        'height':'260px',
                        'shadow':[true, 0.2],
                        'link': linkUrl,
                    });
                }
            ],
            '|', //delimiter
            [
                '新建下级目录', //html code
                function (e) {
                    var path = $(e.data).children().attr('href');
                    var ext = 'dir';
                    buildNewFile(path, ext);

                }
            ],
            [
                '删除目录',
                function (e) {
                    var path = $(e.data).children().attr('href');
                    $.ajax({
                        url:  '/markdown/deleteDir/',
                        type: "POST",
                        data: {
                            link : path,
                        },
                        dataType:"json",
                        success: function (data) {
                            // console.log("response data: ", data.res);
                            alert(data.res);
                            window.location.reload();
                        }
                    });
                }
            ],
        ];
        ContextMenu.render(e, menu, this, 'light')
    });
    $('body').contextmenu(function (e) {
        ContextMenu.render(e,true,this)
    });
})


function buildNewFile(path, ext) {
    PostbirdAlertBox.prompt({
        'title': '请输入名称：',
        'okBtn': '提交',
        onConfirm: function (fname) {
            // console.log("输入框内容是：" + fname);
            // console.log("输入框内容是：" + path);
            // console.log("输入框内容是：" + ext);
            $.ajax({
                url:  '/markdown/createFile/',
                type: "POST",
                data: {
                    link : path,
                    fileName: fname,
                    filetype: ext
                },
                dataType:"json",
                success: function (data) {
                    // console.log("response data: ", data.res);
                    alert(data.res);
                    window.location.reload();
                }
            });
        },
        onCancel: function () {
            console.log("取消输入！");
        },
    });
}

$(function uploadFileDiv() {
    $('#submit-load').click(function uploadFileDiv2() {
        var isXlsx = document.getElementById('isXlsx').checked;
        var link = document.getElementById('link').value;
        var desc = document.getElementById('description').value;
        //获取文件对象，files是文件选取控件的属性，存储的是文件选取控件选取的文件对象，类型是一个数组
        var fileM = document.getElementById('filename');
        var fileObj = fileM.files[0];
        console.log(link);
        console.log(desc);
        console.log(fileObj);
        if (isXlsx) {
            excelupload(link, desc, fileObj);
        } else {
            //创建formdata对象，formData用来存储表单的数据，表单数据时以键值对形式存储的。
            var formData = new FormData();
            formData.append('file', fileObj);
            formData.append('link', link);
            formData.append('description', desc);
            console.log(formData);
            $.ajax({
                url: "/markdown/uploadFileDiv/",
                type: "post",
                dataType: "json",
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (json_data) {
                    // alert("恭喜你！上传成功" + json_data.upload_path);
                    $('#upload_path').html(json_data.upload_path);
                },
            });
        }
    })
})

function excelupload(link, desc, fileObj) {
    // Make sure to get the xlsx file first, and then use the global method window.LuckyExcel to convert
    LuckyExcel.transformExcelToLucky(fileObj, function(exportJson, luckysheetfile) {
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            $('#upload_path').html("Failed to read the content of the excel file, currently does not support xls files!");
        } else {
            // console.log(luckysheetfile);
            $.post(
                '/markdown/uploadExcel/',
                {'link': link, "desc": desc, "sheetdata": luckysheetfile},
                function (data) {
                    console.log(data);
                    $('#upload_path').html(data.upload_path);
                }
            );
        }
    });
}

$(function moveFile(){
    $(document).ready(function(){
        $(".input_button").click(function() {
            var title = $(this).attr("title");       // e.target表示被点击的目标
            console.log(title);
            var inputLink = document.getElementById('title')
            inputLink.setAttribute('value', title)
            $.get(
                '/markdown/getSpaceList/',
                function (data){
                    $("#spaceList").empty();
                    $("#spaceList").append("<option value=\"0\">请选择</option>");
                    $.each (data.spaceList, function(i, item){
                        $("#spaceList").append("<option value=" + item.space + ">" + item.space + "</option>");  //添加一项option
                    })
                }
            );
            $("#moveBox").tooltip("alert",{
                'title':"文件移动至其他目录",
                'backgroundColor': '#c8e5e1',
                'width':'600px',
                'height':'260px',
                'shadow':[true, 0.2],
                'link': title,
            });
        })
    })
})

$(function (){
    $('#spaceList').change(function getDirsList(){
      var space = document.getElementById("spaceList").value;
      $.get(
          '/markdown/getSpaceDirsList/?space=' + space,
          function (data){
              $("#dirList").empty();
              $("#dirList").append("<option value=\"0\">请选择</option>");
              $.each (data.spaceDirsList, function(i, item){
                  console.log(item.upload_dir);
                  var opt = "<option value=" + item.upload_dir + ">" + item.upload_dir + "</option>";
                  console.log(opt);
                  $("#dirList").append(opt);  //添加一项option
              })
          }
      )
    })
})

$(function (){
    $('#act_move').click(function actMove(){
        var title = document.getElementById('title').value;
        var space = document.getElementById('spaceList').value;
        var target_path = document.getElementById('dirList').value;
        $.post(
            '/markdown/moveFile/',
            {"title": title, "space": space, "target_path": target_path},
            function (data){
                $('#move_path').html(data.res);
            }
        );
    })
})

function downExcel(filepath) {
    console.log(filepath);
    $.get(
        '/markdown/getExcelData/?filepath=' + filepath,
        function (data){
            exportExcel(data.sheetdata, data.title);
        }
    )
}